<?php
/***
 * handles user
 *
 *
 **/

require_once 'config.php';

if( !is_string($_REQUEST['type']) ) {
  // error BREAK
}

switch( $_REQUEST['type'] ) {
  case 'REGISTER':
    handleRegister(); break;
  case 'LOGIN':
    handleLogin(); break;
  case 'LOGOUT':
    handleLogout(); break;
  case 'EDIT':
    handleUserEdit(); break;
  default:
    break;
}

function handleRegister() {
  require_once 'db/put/user.php';

  if( is_string($_POST['user']) && is_string($_POST['pass']) 
      && is_string( $_POST['email'] ) ) {

    addUser( $_POST['user'], hash('sha512', (string)($_POST['pass'])), $_POST['email'] );
  } 

  require_once 'tpl/use/Redirect.php';
  skin_Redirect("spit.php");
}
function handleLogin() {
  require_once 'db/get/user.php';

  if( is_string($_POST['user']) && is_string($_POST['pass']) ) {
    $user = loginUser($_POST['user'], hash('sha512', $_POST['pass']));
    // XXX On false login, will user be null or will it be array()?
    if( isset($user['uid']) ) {  
      $_SESSION['uid'] = $user['uid'];
      unset($_SESSION['user']);
      $_SESSION['user']['name'] = $user['name'];
      $_SESSION['user']['perm'] = getPermList( $user['uid'] );
      $user = null;
    } else {
      // redirect to failed login
      $loginSuccess = false;
    }   
  }

  // XXX redirect to previous logged in page.
  require_once 'tpl/use/Redirect.php';
  skin_Redirect("spit.php");
}

function handleLogout() {
  session_destroy();
  require_once 'tpl/use/Redirect.php';
  skin_Redirect("spit.php");
}
?>
